package com.cloud.logger.zchain.zchainclient.interceptor;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * 兼容requestMap请求
 * Created by Administrator on 2017/12/19.
 */
public class MapRequestWrapper extends HttpServletRequestWrapper {

    private Map<String,String[]> paramMap;

    private byte[] requestBody = null;


    public MapRequestWrapper(HttpServletRequest request) {
        super(request);
        paramMap =getParameterMap(request);
        requestBody = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
    }

    public Map<String,String[]> getParameterMap(){
        return paramMap;
    }


    @SuppressWarnings("rawtypes")
    public static Map<String,String[]> getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map<String,String[]> returnMap = new HashMap<String,String[]>();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String[] value = new String[1];
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = new String[1];
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                value = values;
            }else{
                value[0] = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if(requestBody == null){
            requestBody= new byte[0];
        }
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }

    /**
     * 重写 getReader()
     */
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}
